import React, { Component } from "react";
import Pubsub from "pubsub-js";

import eventBus from "../utils/eventBus";

export default class Hello extends Component {
  token: string | null = null;

  state = {
    count: 1,
  };

  componentDidMount() {
    // 消息订阅
    eventBus.on("changeCount", (payload) => {
      console.log("changeCount", payload);

      this.setState((state) => ({
        count: state.count + 1,
      }));
    });

    this.token = Pubsub.subscribe("MSG", (msg, payload) => {
      // 第一个参数指的是消息名字
      // 第二个参数才是发布消息时携带过来的参数
      console.log("MSG", msg, payload);
    });
  }

  componentWillUnmount() {
    // 取消消息订阅
    eventBus.off("changeCount");

    this.token && Pubsub.unsubscribe(this.token);
  }

  render() {
    return (
      <div>
        <h2>Hello</h2>
        <p>count: {this.state.count}</p>
      </div>
    );
  }
}
